<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<link rel="shortcut icon" href="../../share/img/logo.png">
		<link rel="stylesheet" href="../../share/css/main.css">
		<script src="../../share/js/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="../../share/js/util.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body class="p-10">
		<h1>异步</h1>
		<div class="row">
			<div class="col-1">
				<section>
					<h3>定时器</h3>
					<div class="mv-5">
						<button onclick="test1()">setTimeout</button>
					</div>
					<h3>回调函数</h3>
					<div class="mv-5">
						<button onclick="test2()">Ajax 请求</button>
					</div>
					<h3>Promise</h3>
					<div class="mv-5">
						<button onclick="test3()">Promise 请求</button>
					</div>
					<h3>Generator</h3>
					<div class="mv-5">
						<button onclick="test4()">Generator 请求</button>
					</div>
				</section>
			</div>
			<div class="col-1">
				<section>
					<h3>async/await</h3>
					<div class="mv-5">
						<button onclick="test5()">async/await</button>
					</div>
				</section>
			</div>
			<div class="col-1">
				<ul id="log" class="d-list mt-10"></ul>
			</div>
		</div>
		<script>
			function test1() {
				setTimeout(function() {
					util.appendLog("时间到");
				}, 100);
			}

			function test2() {
				$.get("product.json", res => {
					for (let item of res) {
						util.appendLog(`${item.name} , ${item.price}`);
					}
				})
			}

			function test3() {
				function getProducts() {
					return new Promise(function(resolve, reject) {
						$.get("product.json", res => resolve(res));
					});
				}
				getProducts().then(data => {
					for (let item of data) {
						util.appendLog(`${item.name} , ${item.price}`);
					}
				}).catch(err => {
					util.appendLog(err);
				});
			}

			function test4() {
				let it = gen();

				function getProduct() {
					$.get("product.json", res => it.next(res));
				}

				function* gen() {
					let r1 = yield getProduct();
					for (let item of r1) {
						util.appendLog(`${item.name} , ${item.price}`);
					}
					return r1;
				}

				it.next();
			}

			function test5() {
				function f1() {
					return new Promise(function(resolve, reject) {
						util.appendLog("3. 执行 f1 前");
						setTimeout(() => {
							util.appendLog("5. 执行 f1 后");
							resolve('时间1到')
						}, 1000);
					});
				}

				function f2() {
					return new Promise(function(resolve, reject) {
						util.appendLog("3. 执行 f2 前");
						setTimeout(() => {
							util.appendLog("5. 执行 f2 后");
							resolve('时间2到')
						}, 500);
					});
				}
				async function f3() {
					util.appendLog("2. 执行 await 前");
					let r1 = await f1();
					util.appendLog(r1);
					let r2 = await f2();
					util.appendLog(r2);

					util.appendLog("6. 执行 await 后");
				}

				util.appendLog("1. 调用 async 前");
				f3();
				util.appendLog("4. 调用 async 后");
			}
		</script>
	</body>
</html>
